package xyz.hubery.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import xyz.hubery.domain.Market;
import xyz.hubery.domain.UserFavoriteMarket;
import xyz.hubery.model.R;
import xyz.hubery.service.MarketService;
import xyz.hubery.service.UserFavoriteMarketService;

@RestController
@RequestMapping("/userFavorites")
@Api(tags = "用户收藏交易市场管理")
public class UserFavoriteMarketController {

    @Autowired
    private UserFavoriteMarketService service;
    @Autowired
    private MarketService marketService;


    @PostMapping("/addFavorite")
    @ApiOperation(value = "收藏交易市场")
    public R addFavorite(@RequestBody @Validated UserFavoriteMarket userFavoriteMarket) {
        Long userId = Long.valueOf(SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString());
        userFavoriteMarket.setUserId(userId);
        Market market = marketService.getMarketBySymbol(userFavoriteMarket.getSymbol());
        if(market == null) {
            throw new IllegalArgumentException("交易市场不存在");
        }
        userFavoriteMarket.setMarketId(market.getId());
        boolean save = service.save(userFavoriteMarket);
        return save ? R.ok() : R.fail("收藏失败");
    }

    @DeleteMapping("/{symbol}")
    @ApiOperation(value = "取消收藏交易市场")
    public R removeFavorite(@PathVariable String symbol) {
        Market market = marketService.getMarketBySymbol(symbol);
        if(market == null) {
            throw new IllegalArgumentException("交易市场不存在");
        }
        Long userId = Long.valueOf(SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString());
        boolean remove = service.remove(new LambdaQueryWrapper<UserFavoriteMarket>()
                .eq(UserFavoriteMarket::getUserId, userId)
                .eq(UserFavoriteMarket::getMarketId, market.getId())
        );
        return remove ? R.ok() : R.fail("取消收藏失败");
    }
}
